package top.fullj.actor.mq;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author bruce.wu
 * @since 2022/3/4 9:48
 */
class FiberThreadFactory implements ThreadFactory {

    private static final AtomicInteger poolIndex = new AtomicInteger(1);

    private final ThreadGroup group;
    private final AtomicInteger index = new AtomicInteger(1);
    private final String prefix;

    FiberThreadFactory() {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
        prefix = "JActFib#" + poolIndex.getAndIncrement() + "-";
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(group, r,
                prefix + index.getAndIncrement(),
                0);
        if (t.isDaemon())
            t.setDaemon(false);
        if (t.getPriority() != Thread.NORM_PRIORITY)
            t.setPriority(Thread.NORM_PRIORITY);
        return t;
    }
}
